﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TweetSharp.Twitter.Extensions;
using TweetSharp.Twitter.Fluent;
using TweetSharp.Twitter.Model;

namespace Halfwit.Pollers
{
    public class MessagesPoller : TwitterPoller
    {
        public MessagesPoller(Action<TwitterPoller, TwitterResult> callback)
            : base(callback, () => Properties.Settings.Default.MessagesRefreshInterval)
        {
            Description = "Direct Messages";
        }

        protected override ITwitterLeafNode CreateRequest(IFluentTwitter twitter)
        {
            var request = twitter.DirectMessages().Received();
            if (LastId.HasValue)
            {
                request = request.Since(LastId.Value);
            }
            else
            {
                request = request.Take(Properties.Settings.Default.MaxTweets);
            }
            return request;
        }

        protected override void OnSuccessfulRequest(TwitterResult result)
        {
            var tweets = result.AsDirectMessages();
            if (tweets == null || tweets.Count() == 0) return;

            LastId = tweets.Max(t => t.Id);

            TwitterConnection.UpdateFollowers();
        }

        public override IEnumerable<TwitterStatus> ToStatuses(TwitterResult result)
        {
            var messages = result.AsDirectMessages();
            if (messages == null) return Enumerable.Empty<TwitterStatus>();

            return messages.Select(s =>
                new TwitterStatus
                {
                    Id = s.Id,
                    CreatedDate = s.CreatedDate,
                    Text = s.Text,
                    User = s.Sender,
                    Source = HalfwitConstants.DirectMessageSource,
                });
        }
    }
}
